package com.lxmes.base.service.impl;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.lxmes.base.domain.*;
import com.lxmes.base.mapper.JcIteminfoGzMapper;
import com.lxmes.common.exception.ServiceException;
import com.lxmes.common.utils.DateUtils;
import com.lxmes.common.utils.DzGeneraRuleUtils;
import com.lxmes.common.utils.SecurityUtils;
import com.lxmes.common.utils.StringUtils;
import com.lxmes.common.utils.bean.BeanValidators;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.lxmes.base.mapper.JcItembzinfoMapper;
import com.lxmes.base.service.IJcItembzinfoService;
import org.springframework.transaction.annotation.Transactional;

import javax.validation.Validator;

/**
 * 物料标准明细Service业务层处理
 *
 * @author 张志煜
 * @date 2022-11-24
 */
@Service
public class JcItembzinfoServiceImpl implements IJcItembzinfoService
{
    @Autowired
    private JcItembzinfoMapper jcItembzinfoMapper;

    @Autowired
    protected Validator validator;
    @Autowired
    private JcIteminfoGzMapper gzMapper;


    /**
     * 查询物料标准明细
     *
     * @param id 物料标准明细主键
     * @return 物料标准明细
     */
    @Override
    public JcItembzinfo selectJcItembzinfoById(Long id)
    {
        return jcItembzinfoMapper.selectJcItembzinfoById(id);
    }

    /**
     * 查询物料标准明细列表
     *
     * @param jcItembzinfo 物料标准明细
     * @return 物料标准明细
     */
    @Override
    public List<JcItembzinfo> selectJcItembzinfoList(JcItembzinfo jcItembzinfo)
    {
        return jcItembzinfoMapper.selectJcItembzinfoList(jcItembzinfo);
    }


    /**
     * 新增物料标准明细
     *
     * @param jcItembzinfo 物料标准明细
     * @return 结果
     */
    @Override
    public int insertJcItembzinfo(JcItembzinfo jcItembzinfo)
    {
        jcItembzinfo.setCreateTime(DateUtils.getNowDate());
        return jcItembzinfoMapper.insertJcItembzinfo(jcItembzinfo);
    }

    /**
     * 修改物料标准明细
     *
     * @param jcItembzinfo 物料标准明细
     * @return 结果
     */
    @Override
    public int updateJcItembzinfo(JcItembzinfo jcItembzinfo)
    {
        jcItembzinfo.setUpdateTime(DateUtils.getNowDate());
        return jcItembzinfoMapper.updateJcItembzinfo(jcItembzinfo);
    }

    /**
     * 批量删除物料标准明细
     *
     * @param ids 需要删除的物料标准明细主键
     * @return 结果
     */
    @Override
    @Transactional
    public int deleteJcItembzinfoByIds(Long[] ids)
    {
        for(long id : ids) {
            JcItembzinfo bz = jcItembzinfoMapper.selectJcItembzinfoById(id);
            int verify = gzMapper.selectJcIteminfoGzVerify(bz.getItemIdentifyCode());
            if("1".equals(bz.getScFlag()) || verify>0){
                throw new ServiceException(bz.getItemIdentifyCode()+"物料识别码已推送物料生成规则删除失败！！！");
            }
            bz.setCreateBy(SecurityUtils.getUsername());
            bz.setCreateTime(new Date());
            jcItembzinfoMapper.insertJcItembzinfoRerord(bz);
        }
        return jcItembzinfoMapper.deleteJcItembzinfoByIds(ids);
    }
    /*全部删除数据*/
    @Override
    @Transactional
    public int deleteAllItembzinfo() {

        List<JcItembzinfo> jcItembzinfos = jcItembzinfoMapper.selectJcItembzinfoList(null);
        jcItembzinfos.stream().parallel().forEach(bz->{
            bz.setCreateBy(SecurityUtils.getUsername());
            bz.setCreateTime(new Date());
            jcItembzinfoMapper.insertJcItembzinfoRerord(bz);
        });
        return jcItembzinfoMapper.deleteAllItembzinfo();
    }

    /**
     * 删除物料标准明细信息
     *
     * @param id 物料标准明细主键
     * @return 结果
     */
    @Override
    public int deleteJcItembzinfoById(Long id)
    {
        return jcItembzinfoMapper.deleteJcItembzinfoById(id);
    }

    @Override
    @Transactional
    public String imporIteminfo(List<JcItembzinfo> iteminfoList, boolean updateSupport, String operName) {
        if (StringUtils.isNull(iteminfoList) || iteminfoList.size() == 0)
        {
            throw new ServiceException("导入物料数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        for (JcItembzinfo iteminfo : iteminfoList)
        {
            try
            {
                BigDecimal fltgF = iteminfo.getFltgF();
                BigDecimal flnj1 = iteminfo.getFlnj1();
                BigDecimal flnj2 = iteminfo.getFlnj2()==null?new BigDecimal(0.0):iteminfo.getFlnj2();
                String gcylPn = iteminfo.getGcylPn();
                String gctjDn = iteminfo.getGctjDn();

                //1：生成规格型号
                String ggxh = DzGeneraRuleUtils.generaGgxh(fltgF.toString(), flnj1.toString(), flnj2.toString(), gcylPn, gctjDn);
                iteminfo.setSpec(ggxh);
                //2：生成法兰内径
                String flnj = DzGeneraRuleUtils.generaFlnj(flnj1.toString(), flnj2.toString());
                iteminfo.setFlnj(new BigDecimal(flnj));
                //3：生成物料识别码
                BigDecimal flhdC = iteminfo.getFlhdC();
                String itemBzSimCode = iteminfo.getItemBzSimCode();
                BigDecimal flmfmccD = iteminfo.getFlmfmccD();
                BigDecimal flwjD = iteminfo.getFlwjD();
                BigDecimal flghdC = iteminfo.getFlghdC();
                String wlsbm = DzGeneraRuleUtils.generaWlsbm(itemBzSimCode, ggxh, flhdC.toString(), flmfmccD.toString(), fltgF.toString(), flwjD.toString(), flnj, flghdC.toString());
                JcItembzinfo jcItembzinfo = jcItembzinfoMapper.selectJcItembzinfoByItemIdentifyCode(wlsbm);
                if(StringUtils.isNotNull(jcItembzinfo)){
                    throw new RuntimeException("该物料识别码["+wlsbm+"]已存在系统中！");
                }

                iteminfo.setItemIdentifyCode(wlsbm);
                //4：计算重量
                BigDecimal flkjL = iteminfo.getFlkjL();
                BigDecimal flksN = iteminfo.getFlksN();
                Double jszl = DzGeneraRuleUtils.generaJszl(flwjD.toString(), flnj1.toString(), flnj2.toString(), flhdC.toString(), flmfmccD.toString(), fltgF.toString(), flkjL.toString(), flksN.toString());
                iteminfo.setJszl(new BigDecimal(jszl));
                //5：计算下料重量
                Double xlzl = DzGeneraRuleUtils.jsxlzl(flwjD.toString(), flnj1.toString(), flnj2.toString(), flhdC.toString(), fltgF.toString(), gctjDn);
                iteminfo.setXlzl(new BigDecimal(xlzl));

                BeanValidators.validateWithException(validator, iteminfo);
                iteminfo.setCreateBy(operName);
                iteminfo.setTenantId("WR");
                iteminfo.setUpdateBy(operName);
                this.insertJcItembzinfo(iteminfo);
                successNum++;
                successMsg.append("<br/>" + successNum + "、标准 " + iteminfo.getItemBzName() + " 导入成功");
               /* if (StringUtils.isNull(u))
                {
                    BeanValidators.validateWithException(validator, iteminfo);
                    iteminfo.setCreateBy(operName);
                    iteminfo.setUpdateBy(operName);
                    iteminfo.setTenantId(SecurityUtils.getDeptId()+"");
                    this.insertJcItembzinfo(iteminfo);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、标准 " + iteminfo.getItemBzName() + " 导入成功");
                }
                else
                {
                    BeanValidators.validateWithException(validator, iteminfo);
                    iteminfo.setUpdateBy(operName);
                    this.updateJcItembzinfo(iteminfo);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、数据 " + iteminfo.getItemBzName()+ " 更新成功");
                }*/
            }
            catch (Exception e)
            {
                failureNum++;
                String msg = "<br/>" + iteminfo.getItemBzName() + " 导入失败：";
                failureMsg.append(msg + e.getMessage());
            }
        }
        if (failureNum > 0)
        {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new ServiceException(failureMsg.toString());
        }
        else
        {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }




    @Override
    public List<JcItembzinfo> addBZItemInfo(Long[] ids) {
        List<JcItembzinfo> itemList = new ArrayList<>();
        for(long id : ids){
            JcItembzinfo bena = jcItembzinfoMapper.selectJcItembzinfoById(id);
            bena.setHjcbj(0.00);
            bena.setJgcbj(0.0);
            bena.setClcbj(0.0);
            bena.setMfccbj(0.0);
            bena.setLlbj(0.0);
            bena.setSjbj(0.0);
            bena.setTaxRate(0.0);
            bena.setTzxs(0.0);
            bena.setHsbj(0.0);
            bena.setJstj(0.0);
            bena.setJstj(0.0);
            bena.setFlThick(0.0);
            bena.setOrderNum(1);
            if(StringUtils.isNull(bena.getXlzl())){
                bena.setXlzl(new BigDecimal(0));
            }
            if(StringUtils.isNull(bena.getProcessDiffCoe())){
                bena.setProcessDiffCoe(new BigDecimal(0));
            }
            if(StringUtils.isNull(bena.getOrderNumCoe())){
                bena.setOrderNumCoe(new BigDecimal(0));
            }
            itemList.add(bena);
        }
        return itemList;
    }
    //物料标准推送物料生成规则
    @Override
    @Transactional
    public int addItemInfoGz(Long[] ids) {
        for(long id : ids) {
            JcItembzinfo bz = jcItembzinfoMapper.selectJcItembzinfoById(id);
            int verify = gzMapper.selectJcIteminfoGzVerify(bz.getItemIdentifyCode());
            if("1".equals(bz.getScFlag()) || verify>0){
                throw new ServiceException(bz.getItemIdentifyCode()+"物料识别码已推送物料生成规则！！！");
            }
            JcIteminfoGz gz=new JcIteminfoGz();
            gz.setItemBzName(bz.getItemBzName());
            gz.setSpecCode(bz.getItemBzCode());
            gz.setItemName(bz.getItemName());
            gz.setTenantId(bz.getTenantId());
            gz.setClassId("K,P,B,C");
            gz.setClassName("料块,毛坯,半成品,成品");
            gz.setSpec(bz.getSpec());
            gz.setItemIdentifyCode(bz.getItemIdentifyCode());
            gz.setUnit("件");
            gzMapper.insertJcIteminfoGz(gz);
            //修改生成标记
            bz.setScFlag("1");
            jcItembzinfoMapper.updateJcItembzinfo(bz);
        }
        return 1;
    }
}
